#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts()) {
        ui->comboBox->addItem(info.portName());
    }
    connect(&serialPort, &QSerialPort::readyRead, this, &MainWindow::delayReadTimerStart);
    connect(&delayReadTimer, &QTimer::timeout, this, &MainWindow::serialPortRead);
}

MainWindow::~MainWindow()
{
    delete ui;
}

//串口初始化
void MainWindow::serialPortInit()
{
    serialPort.setPortName(ui->comboBox->currentText());
    serialPort.setBaudRate(QSerialPort::Baud115200);
    serialPort.setDataBits(QSerialPort::Data8);
    serialPort.setParity(QSerialPort::NoParity);
    serialPort.setStopBits(QSerialPort::OneStop);
    serialPort.setFlowControl(QSerialPort::NoFlowControl);
}

void MainWindow::analyseFile()
{
    QFile *file = new QFile;
    QString file_str = ui->lineEdit->text();
    file->setFileName(file_str);
    if (!file->open(QIODevice::ReadOnly)) {
        ui->plainTextEdit->insertPlainText(QDateTime::currentDateTime().toString("hh-mm-ss-zzz   ")+"文件打开失败，请检查文件...\n");
        return;
    } else {
        ui->plainTextEdit->insertPlainText(QDateTime::currentDateTime().toString("hh-mm-ss-zzz   ")+"文件打开成功，正在读取文件...\n");
        QFileInfo read_file_info(file_str);
        QDataStream BinFileData(file);  //将刚刚创建的 file 对象的指针传递给一个QDataStream实例 BinFileData
        char *pBuff = new char[read_file_info.size()];  //要读取bin文件的大小
        BinFileData.readRawData(pBuff, static_cast<int>(read_file_info.size()));
        fileSizeAll = static_cast<int>(read_file_info.size());
        sendNumber = static_cast<int>(read_file_info.size()) / 128;
        if (sendNumber % 128 != 0) {
            sendNumber++;
        }
        qDebug()<<"文件大小:"<<fileSizeAll;
        qDebug()<<"总共的包数量:"<<sendNumber;
        dataAllArray = QByteArray(pBuff, static_cast<int>(read_file_info.size()));
        file->close();
        ui->plainTextEdit->insertPlainText(QDateTime::currentDateTime().toString("hh-mm-ss-zzz   ")+"文件读取成功，等待命令...\n");
        ui->pushButton_4->setEnabled(true);
    }
}

void MainWindow::serialPortWrite(QString dataStr)
{
    QString dataSendStr = dataStr + CRC16(dataStr);
    QByteArray byteArray = QByteArray::fromHex(dataSendStr.toUtf8());
    serialPort.write(byteArray);
    qDebug()<<"写入数据"<<byteArray;
}

void MainWindow::timerEvent(QTimerEvent *event)
{
    if (event->timerId() == updateFailedTimer) {
        killTimer(updateFailedTimer);
        ui->plainTextEdit->insertPlainText(QDateTime::currentDateTime().toString("hh-mm-ss-zzz   ") + "升级过程中串口无回复导致升级失败...\n");
        ui->splitter_2->setEnabled(true);
        ui->splitter_3->setEnabled(true);
    }
}

void MainWindow::serialPortRead()
{
    if (delayReadTimer.isActive()) {
        delayReadTimer.stop();
    }
    QByteArray data = serialPort.readAll();
    qDebug()<<"收到数据"<<data;
    if (data.isEmpty()) {
        ui->statusbar->showMessage("无数据");
        return;
    } else {
        ui->statusbar->showMessage("接收数据：" + data);
    }
    if (updateFailedTimer) {
        killTimer(updateFailedTimer);
    }
    if (data == "\x43") {
            ui->plainTextEdit->insertPlainText(QDateTime::currentDateTime().toString("hh-mm-ss-zzz   ") + "发送第一包数据成功，正在升级...\n");
            SendArray();
    } else if (data == "\x06") {
        if (sendNumberSN >= fileSizeAll) {
            QByteArray success;
            success[0] = 0x04;
            serialPort.write(success);
            ui->progressBar->setValue(100);
            ui->plainTextEdit->insertPlainText(QDateTime::currentDateTime().toString("hh-mm-ss-zzz   ") + "程序升级成功...\n");
            ui->splitter_2->setEnabled(true);
            ui->splitter_3->setEnabled(true);
        } else {
            progressBar = (sendNumberSN * 100) / fileSizeAll;
            ui->progressBar->setValue(progressBar);
            SendArray();
        }
    } else if (data == "\x15") {
        QByteArray success;
        success[0] = 0x04;
        serialPort.write(success);
    } else if (data.contains("\x15") && data.contains("\x43")) {
        QByteArray updata_buffer;
        updata_buffer[0] = 0x01;
        updata_buffer[1] = 0xFF;
        updata_buffer[2] = 0x00;
        for (int i = 3; i<131; i++) {
            updata_buffer[i] = 0x00;
        }
    }
}

void MainWindow::delayReadTimerStart()
{
    delayReadTimer.start(50);
}

void MainWindow::SendArray()
{
    QByteArray updata_buffer;//发送的数组
    QByteArray binBuffer;
    for (int i = 0; i < 128; i++) {
        if (sendNumberSN > fileSizeAll) {
            updata_buffer[i] = 0x00;
        } else {
            updata_buffer[i]=dataAllArray[sendNumberSN];
            sendNumberSN++;
        }
    }
    QString a = updata_buffer.toHex();
    QString b = CRC16(a);
    for (int i = 0; i < b.length(); i += 2) {
        // 获取每一对字符，并转成一个字节（16进制）
        QByteArray bytePair = QByteArray::fromHex(b.mid(i, 2).toUtf8());  // 每两个字符转为一个字节
        updata_buffer.append(bytePair);  // 将字节追加到 QByteArray
    }
    updata_buffer.insert(0, 0x01);
    QString key= QString("%1").arg(binSN,2,16,QLatin1Char('0'));
    QByteArray ba1=QByteArray::fromHex (key.toLatin1().data());
    if (binSN < 255) {
        binSN++;
    } else {
        binSN = 0;
    }
    updata_buffer.insert(1,ba1);
    QString key2= QString("%1").arg(binSNOppsoite,2,16,QLatin1Char('0'));
    QByteArray ba2=QByteArray::fromHex (key2.toLatin1().data());
    if (binSN == 0) {
        binSNOppsoite = 255;
    }
    else {
        binSNOppsoite--;
    }
    updata_buffer.insert(2,ba2);
    serialPort.write(updata_buffer);
    updateFailedTimer = startTimer(4000);//检查是否有返回
}

QByteArray MainWindow::intToByte(int i)
{
    QByteArray abyte0;
    abyte0.resize(1);
    abyte0[0]=(i&0x00ff);
    return abyte0;
}

int MainWindow::bytesToInt(uchar bytes)
{
    int addr = bytes& 0xff;
    return addr;
}

//刷新串口
void MainWindow::on_pushButton_clicked()
{
    ui->comboBox->clear();
    foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts()) {
        ui->comboBox->addItem(info.portName());
    }
}

//打开串口
void MainWindow::on_pushButton_2_clicked()
{
    if (ui->pushButton_2->text() == "打开串口") {
        serialPortInit();
        if (!serialPort.open(QIODevice::ReadWrite)) {
            ui->statusbar->showMessage("串口打开失败");
            return;
        } else {
            ui->statusbar->showMessage("串口打开成功");
            ui->pushButton_2->setText("关闭串口");
        }
    } else {
        serialPort.close();
        ui->pushButton_2->setText("打开串口");
        ui->statusbar->showMessage("串口关闭成功");
    }
}

//打开文件
void MainWindow::on_pushButton_3_clicked()
{
    if (!ui->lineEdit->text().isEmpty()) {
        ui->lineEdit->clear();
    }
    QString file_path = QFileDialog::getOpenFileName(this, "请选择文件路径...", "/",tr("files (*.bin)"));
    if (!file_path.isEmpty()) {
        ui->lineEdit->setText(file_path);
        analyseFile();
    } else {
        ui->pushButton_4->setEnabled(false);
        ui->plainTextEdit->insertPlainText(QDateTime::currentDateTime().toString("hh-mm-ss-zzz   ")+"请选择正确的文件...\n");
    }
}

//开始升级
void MainWindow::on_pushButton_4_clicked()
{
    if (!serialPort.isOpen()) {
        QMessageBox::warning(this, "错误", "串口未打开", QMessageBox::Ok);
        return;
    }
    serialPortWrite("0606060606");              //握手
    ui->plainTextEdit->insertPlainText(QDateTime::currentDateTime().toString("hh-mm-ss-zzz   ")+"正在等待产品完成状态转变...\n");
    ui->splitter_2->setEnabled(false);
    ui->splitter_3->setEnabled(false);
    updateFailedTimer = startTimer(4000);//程序升级失败定时器
}

static unsigned char auchCRCHi[]={
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,
0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,
0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,
0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40
};
static unsigned char auchCRCLo[]={
0x00, 0xC0, 0x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xB6, 0x76, 0x72, 0xB2, 0xB3, 0x73, 0xB1, 0x71,
0x70, 0xB0, 0x50, 0x90, 0x91, 0x51, 0x93, 0x53, 0x52, 0x92,
0x96, 0x56, 0x57, 0x97, 0x55, 0x95, 0x94, 0x54, 0x9C, 0x5C,
0x5D, 0x9D, 0x5F, 0x9F, 0x9E, 0x5E, 0x5A, 0x9A, 0x9B, 0x5B,
0x99, 0x59, 0x58, 0x98, 0x88, 0x48, 0x49, 0x89, 0x4B, 0x8B,
0x8A, 0x4A, 0x4E, 0x8E, 0x8F, 0x4F, 0x8D, 0x4D, 0x4C, 0x8C,
0x44, 0x84, 0x85, 0x45, 0x87, 0x47, 0x46, 0x86, 0x82, 0x42,
0x43, 0x83, 0x41, 0x81, 0x80, 0x40
};

QString MainWindow::CRC16(QString data)
{
    QByteArray data_BYTE;
    for (int i = 0; i < data.length(); i += 2) {
        data_BYTE.append(data.mid(i,2).toInt(NULL,16) & 0xFF);
    }
    unsigned char ucCRCHi = 0xFF;
    unsigned char ucCRCLo = 0xFF;
    ushort uIndex = 0;
    ushort i = 0;
    int times=data_BYTE.count();
    while (times--) {
        uIndex = (ushort) (ucCRCHi ^ ((unsigned char)data_BYTE[i++]));
        ucCRCHi = (unsigned char)(ucCRCLo ^ auchCRCHi[uIndex]);
        ucCRCLo = auchCRCLo[uIndex];
    }
    ushort ret = (ushort) ucCRCHi;
    ret = (ret << 8) | ucCRCLo;
    ret = (ret >> 8) | (ret << 8);  // 交换高低字节
    QString str = QString::number(ret, 16);
    if (str.length() != 4) {
        for (; str.length() < 4; i++) {
           str.insert(0,"0");
        }
    }
    return str;
}

//暂时未调用
uint16_t MainWindow::crc16(const QByteArray &data)
{
    uint16_t crc = 0xFFFF;  // CRC 初始值
    for (int i = 0; i < data.size(); i++) {
        crc ^= (data[i] << 8);  // 将字节移到 CRC 的高字节
        for (int j = 0; j < 8; j++) {  // 对每个比特进行处理
            if (crc & 0x8000) {  // 如果 CRC 的高位为 1
                crc = (crc << 1) ^ 0x8005;  // 左移并与多项式异或
            } else {
                crc <<= 1;  // 否则仅左移
            }
        }
    }
    qDebug()<<"CRC值"<<crc;
    return crc;  // Return updated CRC
}

//暂时未调用
unsigned char MainWindow::Check_CRC(const QByteArray &buf, int len)
{
    unsigned short crc = 0;
        // 从数据包的第4字节（索引3）开始校验，128是数据长度
    crc = crc16(buf.mid(0, 128));  // 这里使用 QByteArray::mid() 来获取子数组
    qDebug()<<"checkCRC值"<<crc;
    return crc;
}
